package web

import (
	"embed"
	"io/fs"
	"net/http"

	"github.com/gorilla/mux"
)

//go:embed index.html bootstrap/*
var webFiles embed.FS

// AddRoutes adds the web UI routes to the router
func AddRoutes(router *mux.Router) {
	// Serve the embedded index.html file
	router.HandleFunc("/", serveIndex)
	
	// Serve bootstrap files
	bootstrapFS, err := fs.Sub(webFiles, "bootstrap")
	if err == nil {
		router.PathPrefix("/bootstrap/").Handler(http.StripPrefix("/bootstrap/", http.FileServer(http.FS(bootstrapFS))))
	}
	
	// Serve static files from the root
	rootFS, err := fs.Sub(webFiles, ".")
	if err == nil {
		// Create a catch-all handler for static files that haven't been matched by other routes
		staticHandler := http.FileServer(http.FS(rootFS))
		router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Check if the request is for a bootstrap file
			if _, err := webFiles.ReadFile("bootstrap" + r.URL.Path); err == nil {
				// File exists in bootstrap directory, let the bootstrap handler handle it
				return
			}
			
			// Otherwise, serve the file from the root
			staticHandler.ServeHTTP(w, r)
		})
	}
}

// serveIndex serves the main index.html file
func serveIndex(w http.ResponseWriter, r *http.Request) {
	// Get the index.html file from embedded files
	data, err := webFiles.ReadFile("index.html")
	if err != nil {
		http.Error(w, "Failed to read index.html", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Write(data)
}